import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_div/div.dart';
import 'package:flutter_div/div_style.dart';

class DivButton extends StatefulWidget{

  /// Div按钮
  const DivButton({
    super.key,
    this.style,
    this.styles,
    required this.child,
    this.onTap,
    this.indicator,
    this.loading = false,
    this.disable = false,
  });

  /// 返回false按钮禁用
  final Future<bool?> Function()? onTap;
  final DivStyle? style;
  final List<DivStyle>? styles;
  final Widget child;
  /// 加载中动画组件
  final Widget? indicator;
  final bool loading;
  final bool disable;
  
  @override
  createState() => _DivButtonState();
}

class _DivButtonState extends State<DivButton> {

  late bool loading = widget.loading;
  late bool disable = widget.disable;

  ///加载中动画
  Widget _loadingIndicator(){

    final renderBox = context.findRenderObject() as RenderBox?;
    final size = (renderBox?.size.height??0)/2;

    return widget.indicator ?? Center(
      child: Container(
        constraints: BoxConstraints(
          minWidth: 10, maxWidth: 30,
          minHeight: 10, maxHeight: 30,
        ),
        width: size, height: size,
        child: CircularProgressIndicator(
          value: null, // 当value为null时，表示动画处于无限循环状态
          strokeWidth: 1.5, // 进度条宽度
          color: Colors.white, // 进度条颜色
          strokeCap: StrokeCap.butt,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {

    var loadingStyle = DivStyle(color: Colors.transparent).merge(widget.style);
    loadingStyle = loadingStyle.copyWith(color: loadingStyle.color?.withOpacity(0.7));

    var disableStyle = DivStyle(color: Colors.transparent).merge(widget.style);
    disableStyle = loadingStyle.copyWith(color: loadingStyle.color?.withOpacity(0.5));

    return Div(
      key: widget.key,
      child: loading ? _loadingIndicator() : widget.child,
      style: loading ? loadingStyle : disable ? disableStyle : widget.style,
      styles: widget.styles,
      onTap: ()async{
        if(widget.onTap!=null && loading==false && disable==false){
          loading = true;
          setState(() {});
          var res = await widget.onTap!.call();
          if(res == false){
            loading = false;
            disable = true;
          }else{
            loading = false;
          }
          setState(() {});
        }
      },
    );
  }
}
